/****************************
 * 组织: 烤爆米实验室洪荒团队
 * 编写人: 董书承
 * 时间: 12_1_2021
 * 内容:
 *     a. 虚拟环境类
 *      a1. 分裂环境名字和版本号
 *      a2. 安装虚拟环境.
 *          出现问题: 需要在setenv上更新内容: 即把文件安装到哪个文件夹
 ****************************/
# include "virenv.hh"
# include <string>
# include "setpython.hh"
# include <iostream>
# include <vector>
# include "demsStr.hh"
# include <pwd.h>
# include "files.hh"
# include "dlCommd.hh"
# include "status.hh"
# include <fstream>
# include "infoSys.hh"
# include <unistd.h>

void Venv::splNameVer()
{
    for (const std::string& temp: this->dEnv)
    {
        std::vector <std::string> eachEnv = strSplit(temp, "=");
        this->envName.push_back(eachEnv[0]);
        this->envVer.push_back(eachEnv[1]);
    }

}

void Venv::instEnv() {
    // 获取安装的环境有几个
    int envNum = this->envName.size();
    // 一一对应采用setenv的方式安装.
    for (int i = 0; i < envNum; i++)
    {
        dShell::envset(this->envName[i], this->envVer[i]);
    }
    //装好以后, 将这些信息写到文件中
    passwd* pwd;
    pwd = getpwuid(getuid());
    std::string userName = pwd->pw_name;

    std::system("mkdir -p ~/.data/dems/virenv 2>/dev/null");
    std::ofstream envFle("/home/"+userName+"/.data/dems/virenv/envLists.dms", std::ios::out|std::ios::app);
    envFle << this->name + " ";
    for(int i = 0; i<envNum; i++)
    {
        // 格式: 虚拟环境名 开发环境名=版本号 开发环境名=版本号 python=Conda虚拟环境的名称
        envFle << this->envName[i] + "=" + this->envVer[i] << " ";

    }
    envFle << std::endl;


}

int actiVenv(std::string envName)
{
    std::string userName = getUsrNme();

    // 查找环境激活文件, 如果没有, 则报没有这个环境退出返回FAIL
    std::string envInfo = getFmFile_starting(VIRENVINFOPOS,envName);
    if (envInfo == "FAIL TO FIND IN PATH\n" + VIRENVINFOPOS) // 特别报错提示
    {
        std::cout << "没有这个环境名, 请检查拼写或创建环境" << std::endl;
        return FAIL;
    }
    // 找到了, 得到的是这一行的信息, 需要分解
    std::vector <std::string> envinfoList = strSplit(envInfo, " "); // 第一条一定是环\
                                            //境名字, 剩下的一定是 "开发环境 = 版本号" 的形式.
                                                                    
    std::vector <std::string> devEnvName, devEnvVer;
    for(int i = 1; i<=envinfoList.size()-1; i++)
    {
        std::vector <std::string> temp;
        temp = strSplit(envinfoList[i], "=");
        devEnvName.push_back(temp[0]);
        devEnvVer.push_back(temp[1]);
        std::cout << temp[0] << std::endl << temp[1] << std::endl;
    }
    for (int i = 0; i<=devEnvName.size(); i++)
    {
        if (devEnvName[i] == "python")
        {
            envset("p_v"+devEnvVer[i]);
        }
        else
        {
            dShell::envset(devEnvName[i], devEnvVer[i]);
        }
    }
    



}